package cn.yuli.zookeeper.master;

import java.io.IOException;
import java.util.Random;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class Master implements Watcher {
	
	private static Logger logger = Logger.getLogger(Master.class);
	
	private ZooKeeper zk;//zk客户端
	private String host;//地址
	private String serverId = Integer.toHexString(new Random().nextInt());//产生服务id
	private boolean isLeader = false;
	public Master(String host) {
		this.host = host;
	}
	public void process(WatchedEvent event) {
		System.out.println(event);
	}
	
	
	public void runForMaster() throws InterruptedException{
		while(true){
			try {
				zk.create("/master", serverId.getBytes(),Ids.OPEN_ACL_UNSAFE , CreateMode.EPHEMERAL);
				isLeader = true;
				logger.info("成功当选主节点");
				break;
			} catch (KeeperException e) {
				if(e instanceof NodeExistsException){
					logger.info("节点已经存在，你不是主节点");
					isLeader = false;
					break;
				}
			}
			if(checkMaster()){
				break;
			}
		}
	}
	
	public boolean checkMaster() throws InterruptedException{
		while(true){
			try {
				Stat stat = new Stat();
				byte[] data = zk.getData("/master", false, stat);
				isLeader = new String(data).equals(serverId);
				return true;
			} catch (KeeperException e) {
				if(e instanceof NoNodeException){
					logger.info("没有节点，请重新尝试获取节点");
					return false;
				}
			} 
		}
	}
	
	public void startZK() throws IOException{
		zk = new ZooKeeper(host, 15000, this);
	}
	public void stopZK() throws InterruptedException{
		zk.close();
	}
	
	
	public static void main(String[] args) throws IOException, InterruptedException {
		Master m = new Master("39.108.170.73:2181");
		m.startZK();
		m.runForMaster();
		if(m.isLeader){
			logger.info("我已经成为了主节点");
			Thread.sleep(6000);
		}else{
			logger.info("有人已经成为了主节点");
		}
		m.stopZK();
	}
	

}
